package code.network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import code.exceptions.DataMaxSizeException;
import code.wrtp.Constants;

public class PacketTx {

	private DatagramSocket datagramSocket;
	private String subNet;
	private short port;
	private AddressUtil addressUtil;

	public PacketTx(String subNet, short port, AddressUtil addressUtil) {

		try {
			this.port = port;
			this.subNet = subNet;
			datagramSocket = new DatagramSocket(port + 1);
			this.addressUtil = addressUtil;
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}

	public boolean transmitPacket(short dStation, byte[] info) {
		try {
			/* IF info.length <= MAX_CAPACITY */
			if (info.length <= Constants.MAX_PACKAGE_SIZE) {
				InetAddress IPAddress;
				DatagramPacket sendDatagramPacket;
				if (dStation == Constants.BROADCAST_ADDRESS) {
					IPAddress = InetAddress.getByName(addressUtil
							.makeAddressForInet(dStation,
									Constants.BROADCAST_PREFIX));
					datagramSocket.setBroadcast(true);
					sendDatagramPacket = new DatagramPacket(info, info.length,
							IPAddress, port + 1);
				} else {
					IPAddress = InetAddress.getByName(addressUtil
							.makeAddressForInet(dStation, subNet));
					datagramSocket.setBroadcast(false);
					sendDatagramPacket = new DatagramPacket(info, info.length,
							IPAddress, port);
				}
				datagramSocket.send(sendDatagramPacket);
				return true;
			} else {
				throw new DataMaxSizeException(
						"Package size bigger than allowed!");
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
			return false;
		} catch (SocketException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} catch (DataMaxSizeException e) {
			e.printStackTrace();
			return false;
		}
	}

	public void closeSocket() {
		datagramSocket.close();
	}
}
